﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web;
using System.Xml;
using System.Text;

namespace _18miljard.Mail
{
	public class PostScriptumCollection : Collection<PostScriptum>
	{
		private PostScriptum currentPostScriptum = null;
		private Random random;

		public PostScriptumCollection()
			: base()
		{
			this.random = new Random();
			this.ReadPostScriptums();
		}

		private void ReadPostScriptums()
		{
			string path = HttpContext.Current.Server.MapPath("/App_Data/Mail.xml");
			XmlDocument doc = new XmlDocument();
			doc.Load(path);

			XmlNodeList nodes = doc.SelectNodes("/miljard/postscriptum");

			foreach (XmlNode node in nodes)
			{
				this.Add(this.ReadPostScriptum(node));
			}

			doc.RemoveAll();
		}

		private PostScriptum ReadPostScriptum(XmlNode node)
		{
			XmlAttribute attr = node.Attributes["id"];
			int id = XmlConvert.ToInt32(attr.Value);

			attr = node.Attributes["probability"];
			double prob = XmlConvert.ToDouble(attr.Value);

			StringBuilder str = new StringBuilder(node.InnerText);
			str.Replace("\r\n", "");
			str.Replace("\t", "");

			return new PostScriptum(id, str.ToString(), prob);
		}

		public PostScriptum FindID(int id)
		{
			if (this.currentPostScriptum.Id == id)
				return this.currentPostScriptum;

			foreach (PostScriptum ps in this)
				if (ps.Id == id)
					return ps;

			return null;
		}

		protected override void InsertItem(int index, PostScriptum item)
		{
			if (this.currentPostScriptum == null || item.Id > this.currentPostScriptum.Id)
				this.currentPostScriptum = item;

			base.InsertItem(index, item);
		}

		public PostScriptum CurrentPostScriptum
		{
			get { return this.currentPostScriptum; }
		}

		public double RandomValue
		{
			get
			{
				return this.random.NextDouble();
			}
		}
	}
}